import { cn } from "@/lib/utils";
import { forwardRef, useState, useEffect } from "react";

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  variant?: string;
  errorFlag?: boolean;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
/**
 * 输入框组件
 * @param {string} className - 自定义类名
 * @param {string} type - 输入框类型，默认为 "text"
 * @param {boolean} errorFlag - 封装错误框逻辑
 */
import { Ref } from "react";
const Input = forwardRef(
  (
    { className, type, errorFlag = false, onChange, ...props }: InputProps,
    ref: Ref<HTMLInputElement>,
  ) => {
    const [onChangeCloseError, setOnChangeCloseError] =
      useState<boolean>(errorFlag);

    useEffect(() => {
      setOnChangeCloseError(errorFlag);
    }, [errorFlag]);

    return (
      <div>
        <input
          type={type}
          className={cn(
            "flex h-10 w-full rounded-md border border-input px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
            onChangeCloseError
              ? "border-red-500 ring-2 ring-red-500 outline-red-500"
              : "",
            className || "",
          )}
          onChange={(e) => {
            if (onChange) {
              onChange(e);
            }
            setOnChangeCloseError(false);
          }}
          ref={ref}
          {...props}
        />
      </div>
    );
  },
);

Input.displayName = "Input";

export { Input };
export type { InputProps };
